package net.wanho.config;

import net.wanho.shiro.filter.JwtFilter;
import net.wanho.shiro.matcher.JwtMatcher;
import net.wanho.shiro.realm.ShiroRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2023-08-23 16:18
 * Description：<描述>
 */
@Configuration
public class ShiroConfig {

    /**
     * ShiroFilter，对资源进行过滤处理
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 自定义过滤器
        Map<String, Filter> filterMap = new LinkedHashMap<>();
        filterMap.put("jwtFilter", new JwtFilter());
        shiroFilterFactoryBean.setFilters(filterMap);

        // 设置过滤规则
        Map<String,String> map = new LinkedHashMap<>();
        // 设置放行的资源
        map.put("/captchaImage", "anon");
        map.put("/login", "anon");
        // 放行knife4j相关资源
        map.put("/doc.html", "anon");
        map.put("/webjars/**", "anon");
        map.put("/swagger-resources/**", "anon");
        map.put("/v2/api-docs", "anon");
        map.put("/swagger-ui.html", "anon");

        map.put("/**", "jwtFilter");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }

    /**
     * 安全管理器
     */
    @Bean
    public DefaultWebSecurityManager defaultSecurityManager(Realm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }

    /**
     * 自定义Realm
     */
    @Bean
    public Realm realm(){
        ShiroRealm realm = new ShiroRealm();

        JwtMatcher jwtMatcher = new JwtMatcher();
        realm.setCredentialsMatcher(jwtMatcher);

        return realm;
    }

}
